import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'

enum TIP {
  UPLOADED = 'GENERAL.INFO.UPLOADED',
  NOT_UPLOAD = 'GENERAL.INFO.NO_UPLOAD',
}

@Component({
  selector: 'app-new-upload-file',
  templateUrl: './new-upload-file.component.html',
  styleUrls: ['./new-upload-file.component.less'],
})
export class NewUploadFileComponent implements OnInit {

  tipEnum = TIP
  isShowTip: boolean
  tip: string = TIP.NOT_UPLOAD
  @Output() contentChange = new EventEmitter()
  @Input() content: string

  @Input() disable: boolean
  constructor() {}

  ngOnInit() {
    if (!this.content) {
      this.tip = TIP.NOT_UPLOAD
    } else {
      this.tip = TIP.UPLOADED
    }
    this.isShowTip = true
  }

  handleFile(event: any): void {
    try {
      this.isShowTip = false
      const target = event.target
      if (target) {
        const file = target.files[0]
        const name = file.name
        const reader = new FileReader()
        reader.readAsText(file, 'UTF-8')
        const that = this
        reader.onload = (evt) => {
          const evtTarget = evt.target as FileReader
          that.content = evtTarget.result as string
          that.contentChange.emit(evtTarget.result as string)
          that.isShowTip = true
          that.tip = name || 'GENERAL.INFO.UPLOADED'
        }
      }
    } catch (e) {
      console.error(e.message)
    }
  }
}
